import React, { useMemo } from 'react';
import _ from 'lodash';
import { nanoid } from 'nanoid';
import { Table } from 'antd';
import styles from './index.less';

export const defaultColumnWidth = 160;

export default ({ indexRender, columns, size, paging }) => {
  const dataSource = useMemo(
    () => _.map(new Array(paging.size || 10), () => ({ id: nanoid(12) })),
    [paging],
  );

  const { scrollX, tableColumns } = useMemo(() => {
    const nextTableColumns = [...(columns || [])];
    if (indexRender) {
      const index = _.findIndex(nextTableColumns, ({ id }) => id === 'index');
      if (index === -1) {
        nextTableColumns.unshift({
          id: 'index',
          width: 80,
          title: '序号',
          dataIndex: 'index',
          align: 'center',
        });
      }
    } else {
      const index = _.findIndex(nextTableColumns, ({ id }) => id === 'index');
      if (index > -1) {
        nextTableColumns.splice(index, 1);
      }
    }
    const nextScrollX = _.reduce(
      nextTableColumns,
      (sum, item) => sum + (item.width || defaultColumnWidth),
      0,
    );

    return {
      scrollX: nextScrollX,
      tableColumns: nextTableColumns,
    };
  }, [columns, indexRender]);

  return (
    <div className={styles.tableContainer}>
      <Table
        bordered
        rowKey="id"
        size={size}
        scroll={{ x: scrollX, y: 496 }}
        columns={tableColumns}
        dataSource={dataSource}
        pagination={
          _.isEmpty(paging)
            ? false
            : {
                small: 'small',
                simple: false,
                showQuickJumper: true,
                showSizeChanger: true,
                total: 0,
                current: 1,
                pageSize: paging.size,
                showTotal: (text, range) =>
                  `${range.length ? '第' + range.join('~') + '条 / ' : ''}共${text}条`,
              }
        }
      />
    </div>
  );
};
